package com.alpha.eceasy.mall.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alpha.eceasy.extension.BaseServiceImpl;
import com.alpha.eceasy.mall.api.entity.MallCommodityCategory;
import com.alpha.eceasy.mall.api.vo.MallCommodityCategoryVO;
import com.alpha.eceasy.mall.mapper.MallCommodityCategoryMapper;
import com.alpha.eceasy.mall.service.MallCommodityCategoryService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service
public class MallCommodityCategoryServiceImpl extends BaseServiceImpl<MallCommodityCategoryMapper, MallCommodityCategory>
        implements MallCommodityCategoryService {
    @Override
    public IPage<MallCommodityCategoryVO> getMallCommodityCategoryVOPage(Page<MallCommodityCategory> page,
                                                                         MallCommodityCategory mallCommodityCategory) {
        return this.page(page, Wrappers.<MallCommodityCategory>lambdaQuery()
                        .like(StrUtil.isNotEmpty(mallCommodityCategory.getName()),
                                MallCommodityCategory::getName, mallCommodityCategory.getName())
                        .eq(ObjectUtil.isNotEmpty(mallCommodityCategory.getLevel()),
                                MallCommodityCategory::getLevel, mallCommodityCategory.getLevel())
                        .eq(ObjectUtil.isNotEmpty(mallCommodityCategory.getParentGuid()),
                                MallCommodityCategory::getParentGuid, mallCommodityCategory.getParentGuid())
                        .eq(ObjectUtil.isNotEmpty(mallCommodityCategory.getState()),
                                MallCommodityCategory::getState, mallCommodityCategory.getState())
                        .eq(MallCommodityCategory::getDeleted, false))
                .convert(commodityCategory -> {
                    MallCommodityCategoryVO vo = new MallCommodityCategoryVO(commodityCategory);
                    vo.setChildren(this.list(Wrappers.<MallCommodityCategory>lambdaQuery()
                            .eq(MallCommodityCategory::getParentGuid, commodityCategory.getGuid())));
                    String parentGuid = commodityCategory.getParentGuid();
                    if (StrUtil.isNotBlank(parentGuid)) {
                        vo.setParentName(this.getByGuid(parentGuid).getName());
                    }
                    return vo;
                });
    }
}
